# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name:        FilePersistence.py
# Purpose:
#
# Author:      Drago@
#
# Created:     06.08.2009
# Copyright:   (c) Drago@ 2009
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import Pyro.core

from pygs.interfaces import IPersistenceInterface, BaseService
from pygs.logger import logger

class FilePersistence(BaseService, Pyro.core.ObjBase, IPersistenceInterface):
    """
        File persistence implementation
    """

    fileName = None

    def __init__(self):
        Pyro.core.ObjBase.__init__(self)

    def startup(self, params = None):
        BaseService.startup(self, params)
        assert params or self.params, 'Must define params for startup service!'
        if params:
            self.params = params
        # open file for write
        self.fileName = params["fileName"]
        self.dataFile = open(self.fileName, "a")
        logger.log("File '%s' is opened for wright." % self.fileName)

    def shutdown(self):
        BaseService.shutdown(self)
        self.dataFile.close()
        logger.log("File '%s' is closed." % self.fileName)

    def addPoints(self, trackingObject, points):
        # wright data
        for point in points:
            formattedPoint = ("Tracing object: %s, latitude: %s, longitude: %s, time: %s\n" %
                (trackingObject, point.latitude, point.longitude, point.time))
            self.dataFile.write(formattedPoint)
            # flush data from buffer
            self.dataFile.flush()
            logger.log("Point to save: %s" % formattedPoint)

